<template>
<div>
    <div class="e-form">
        <BillTop title="采购计划编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="计划明细" name="changeDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="变更历史" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.planBuy" label-width="170px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                        <span>{{ formData.planBuy.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划日期：" prop="billDate">
                                            <el-date-picker
                                                v-model="formData.planBuy.billDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="采购人：" prop="buyer">
                                            <el-input readonly v-model="formData.planBuy.buyer" placeholder="选择人员">
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectBuyer"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种：" prop="currencyId">
                                        <el-select
                                                v-model="formData.planBuy.currencyId"
                                                placeholder="请选择"
                                                @change="currencyChange"
                                            >
                                                <el-option
                                                    v-for="(
                                                        item
                                                    ) in currencyForm"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="费用合计（元）：">
                                            <span>{{ formData.planBuy.purchaseCost }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更期数：">
                                            <span>{{ formData.planBuy.number }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ userInfo.orgInfo.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报人：">
                                            <span>{{ formData.planBuy.recorder }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.planBuy.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="备注：">
                                        <el-input type="textarea" v-model="formData.planBuy.remarks"></el-input>
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：" >
                                            <span>{{ formData.planBuy.baseCurName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.planBuy.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币汇率：" prop="baseCurRate">
                                            <el-input
                                                v-model="formData.planBuy.baseCurRate"
                                                @blur="onScSumCost"
                                                v-enter-float2="{
                                                    set: formData,
                                                    val: 'planBuy',
                                                    key: 'baseCurRate'
                                                }"
                                                placeholder="请输入内容"
                                            :disabled="!showBaseCurName"
                                                clearable>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="12">
                                        <el-form-item label="费用合计（本位币）：">
                                            <span>{{formData.planBuy.baseCurPurchaseCost}}</span>
                                        </el-form-item>
                                    </el-col> -->
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="changeDetailCon" class="con">
                        <div class="tabs-title" id="changeDetail">计划明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="selectEquip">选择基础库设备</el-button>
                                        <el-button  class="btn-greenYellow" @click="selectYear">选择年度采购预算登记</el-button>
                                        <el-button  class="btn-delete" @click="deletePlanList " v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('planDetail')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="planConfigurationDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': planConfigurationDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column type="selection" align="center" width="55" v-if="isBatch[0].flag"></el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                 <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    align="left"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.specificationModel" clearable></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="单位"
                                    width="120"
                                    align="center"
                                    prop="unit"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="数量"
                                    width="130"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.quantity" clearable
                                        @input="curStateChange(row)"
                                        v-enter-integer1="{
                                            set: row,
                                            key: 'quantity'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价（元）"
                                    width="130"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.price" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key:'price'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                               <el-table-column
                                    prop="amount"
                                    label="金额（元）"
                                    width="100"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="predictTime"
                                    label="预计进场时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker
                                            v-model="row.predictTime"
                                            type="date"
                                            placeholder="选择日期"
                                            value-format="yyyy-MM-dd"
                                            :clearable="false"
                                        >
                                        </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseType"
                                    label="建议采购方式"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select v-model="row.leaseType" @input="curStateChange(row)">
                                            <el-option
                                                v-for="(item,index) in tenderForm"
                                                :label="item.label"
                                                :value="item.value"
                                                :key="index
                                            ">
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">变更历史</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="changeHistorySelect"
                                :data="changeHistoryTable"
                                border
                                @selection-change="changeHistoryTableSelect"
                                v-sortTable="{ 'tableData': changeHistoryTable, '_this': this, 'ref': 'changeHistorySelect' }"
                            >
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{row}">
                                       <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteHistory(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeBillNo"  align="center" label="变更编号" show-overflow-tooltip min-width="200" class-name="blue-column">
                                    <template slot-scope="{ row }" >
                                        <span @click="tableDbShow(row)">{{row.changeBillNo}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="changeBillDate"
                                    label="变更日期"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="机构"
                                    width="200"
                                    align="left"
                                    show-overflow-tooltip min-width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseCost"
                                    label="变更前金额"
                                    align="right"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="changePurchaseCost"
                                    label="变更后金额"
                                    align="right"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="变更期数"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="120"
                                    align="center"
                                >
                                    <template slot-scope="{row}">
                                        <span>{{statusLable(row.state)}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="5014"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
         </div>
         <div id="seat" :style="{height: seatHeight + 'px'}"></div>
         <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.planBuy.state" @exas="exas" :founderId="formData.planBuy.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</div>

</template>

<script>
import { mapState, mapMutations } from 'vuex'
import request from '@/api/equip/equipPlan.js'
import count from '@/api/equip/equipPlanCount.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading, selectDataClient, showLoading } from '@/utils/common'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
import requestAudit from '@/api/equip/common.js'
import { selectUserBelowOrg, selectEquipmentBase } from '@/api/equip/popupCallback.js'
export default {
    data () {
        return {
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //基础信息
                'planBuy': {
                    'auditTime': '',
                    'auditor': '',
                    'auditorId': '',
                    'baseCurId': '',
                    'baseCurName': '',
                    'baseCurPurchaseCost': 0,
                    'baseCurRate': null,
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'buyer': '',
                    'buyerId': '',
                    'changeBillDate': '',
                    'changeBillId': '',
                    'changeBillNo': '',
                    'changePurchaseCost': 0,
                    'changeState': 0,
                    'currency': '',
                    'currencyId': '',
                    'founderId': '',
                    'founderName': '',
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'number': 0,
                    'orgId': '',
                    'orgName': '',
                    'purchaseCost': 0,
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'rmbId': '',
                    'rmbName': '',
                    'rmbRate': 0,
                    'rmbSumPurchaseCost': 0,
                    'state': 0,
                    'version': 0,
                    'workId': '',
                    'yearBudgetPlanId': '',
                    'yearBudgetPlanNo': ''
                }
            },
            rules: {
                billDate: [
                    { required: true, message: '请选择日期', trigger: 'blur' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'change'  },
                ],
                buyer: [
                    { required: true, message: '请选择采购人', trigger: 'change' },
                ],
                baseCurRate: [
                    { required: true, message: '请输入本位币汇率', trigger: 'change' },
                    { validator: (rule, value, callback)=>{
                        if(value == 0) {
                            callback(new Error('本位币汇率必须大于0'))
                        }else{
                            callback()
                        }
                    }, trigger: 'change' }
                ]
            },
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 5014,  //配置计划
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 5014,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            showBaseCurName: false,
            billid: this.$route.query.billid,
            planConfigurationDtlList: [], //计划明细
            planConfigurationDtlListCopy: [],
            planSelect: [], //计划明细选择项
            changeHistoryTable: [], //变更历史
            changeHistorySelect: [], //变更历史选择项
            auditHistoryTable: [],
            userId: '',
            currentRow: {}, //计划明细当前行数据
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            tenderForm: state => state.biddingApplication.dictionaries.tenderForm, //招标方式
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //当前单据状态
        state () {
            return this.formData.planBuy.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //监听时间变化
        'formData.planBuy.billDate': function (newDate, oldDate) {
            let newYaer =  new Date(newDate).getFullYear()
            let oldYaer =  oldDate ? new Date(oldDate).getFullYear() : 0
            console.log(newYaer, oldYaer)
            if(oldYaer !== 0) {
                if(newYaer !== oldYaer) {
                    this.planConfigurationDtlListCopy = []
                    for(let i = this.planConfigurationDtlList.length;i > 0 ;i--) {
                        if(this.planConfigurationDtlList[i - 1].buyPlanDtlId) {
                            this.$set(this.planConfigurationDtlList[i - 1], 'changeType', -1)
                        }else{
                            this.planConfigurationDtlList.splice(i - 1, 1)
                        }
                    }
                }
            }
        }
    },
    created () {
        this.userId = localStorage.getItem('userId')
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'changeDetail', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'changeHistory':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.changeHistorySelect.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }

        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //去变更新增页面
        handleChange () {
            const billid = this.billid
            this.$router.push({
                path: '/housePurchasePlanChangeAdd',
                query: { billid }
            })
        },
        //去变更编辑页面
        tableEdit (billid) {
            this.$router.push({
                path: '/housePurchasePlanChangeEdit',
                query: { billid }
            })
        },
        //变更查看页面
        tableDbShow (row) {
            this.auditParams.billId = row.billId
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
                if( this.auditState.canModify == true) {
                    this.$router.push({
                        path: '/housePurchasePlanChangeEdit',
                        query: { billid: row.billId }
                    })
                }else{
                    this.$router.push({
                        path: '/housePurchasePlanChangeShow',
                        query: { billid: row.billId }
                    })
                }
            })
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getChangeHistory(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            requestAudit.history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //基本信息查询
        getInfo () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.purchaseBaseInfo(params).then(res=>{
                this.formData.planBuy = res.planBuy
            })
        },
        //计划明细查询
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.purchasePlanInfo(params).then(res=>{
                this.planConfigurationDtlListCopy = []
                this.planConfigurationDtlList = res.planBuyDtlList
                res.planBuyDtlList.map(item=>{
                    this.planConfigurationDtlListCopy.push(item)
                })
            })
        },
        //币种切换
        currencyChange (val) {
            this.formData.planYearBudget.currency = this.currencyForm.find(x=>x.value === val).label  //币种
            requestAudit.getRmbRate({  //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId
            }).then(res=>{
                if(res.rate === 1) {
                    this.formData.planYearBudget.rmbId = res.currency
                    this.formData.planYearBudget.rmbRate = res.rate
                }else{
                    this.formData.planYearBudget.rmbId = res.rateId
                    this.formData.planYearBudget.rmbRate = res.rate
                }
            }).catch(()=>{

            })
            if(this.formData.planYearBudget.currencyId === this.formData.planYearBudget.baseCurId) {   //币种=本位币
                this.formData.planYearBudget.baseCurRate = 1
                this.showBaseCurName = false
            }else{
                this.formData.planYearBudget.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        //变更历史查询
        getChangeHistory () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getPurchasePlanChangeHistory(params).then(res=>{
                this.changeHistoryTable = res.planBuyList
            })
        },
        /**选择采购人（选择本机构及下级机构组织人员） */
        selectBuyer () {
            let obj = {
                title: '选择采购人'
            }
            selectUserBelowOrg(obj).then(res=>{
                this.formData.planBuy.buyer = res.userName
                this.formData.planBuy.buyerId = res.userId
            })
        },
        /* 计划明细 */
        //选择设备基础库
        selectEquip () {
            //判断是否做了该年度的预算登记
            request.getYearBudgetEquip(this.formData.planBuy.billDate).then(res=>{
                if(res.length === 0) {
                    this.clientPop(
                        'err',
                        '请先做年度登记预算!',
                    )
                }else{
                    let json = {
                        'categoryId': '00000',
                        'isUpdate': false,
                        'keyword': ''
                    }
                    selectEquipmentBase(json).then(res=>{
                        res.forEach(item=>{
                            let obj = {
                                'amount': 0,
                                'billId': this.billid,
                                'billNo': '',
                                'buyPlanDtlId': '',
                                'categoryId': '',
                                'categoryName': '',
                                'changeType': 1,
                                'equipmentId': '',
                                'equipmentName': '',
                                'oldState': null,
                                'oneLevelCategoryId': '',
                                'oneLevelCategoryName': '',
                                'predictTime': '',
                                'price': null,
                                'quantity': null,
                                'specificationModel': '',
                                'state': null,
                                'unit': '',
                                ...item
                            }
                            obj.state = null
                            this.planConfigurationDtlList.push(obj)
                            this.planConfigurationDtlListCopy.push(obj)
                        })
                    })
                }
            })
        },
        //选择年度登记预算
        selectYear () {
            request.getYearBudgetEquip(this.formData.planBuy.billDate).then(res=>{
                if(res.length === 0) {
                    this.clientPop(
                        'err',
                        '请先做年度登记预算!',
                    )

                }else{
                    let ids = []
                    ids = this.planConfigurationDtlListCopy.map(x=>x.yearBudgetDtlId)
                    selectDataClient({
                        SelectServiceToken: '/facilityplan/year/budget/equip', // 客户端对应方法名
                        IsSingleMode: false, // 是否单选 true 单选 false 多选
                        SelectedIDs: ids, // 已选中id
                        InitParamsStr: JSON.stringify(this.formData.planBuy.billDate),    // 接口参数
                        Title: '选择年度采购预算登记' // 标题
                    }).then(val => {
                        this.setSelectedInfo(val)
                        val.forEach(item=>{
                            let obj = {
                                'amount': 0,
                                'billId': '',
                                'billNo': '',
                                'buyPlanDtlId': '',
                                'categoryId': '',
                                'categoryName': '',
                                'changeType': 1,
                                'equipmentId': '',
                                'equipmentName': '',
                                'oldState': 0,
                                'oneLevelCategoryId': '',
                                'oneLevelCategoryName': '',
                                'predictTime': '',
                                'price': 0,
                                'quantity': 0,
                                'specificationModel': '',
                                'state': 0,
                                'unit': '',
                                'yearBudgetDtlId': '',
                                ...item
                            }
                            obj.billId = this.billid
                            obj.price = null
                            obj.quantity = null
                            obj.amount = null
                            this.planConfigurationDtlList.push(obj)
                            this.planConfigurationDtlListCopy.push(obj)
                        })
                        this.itemObj = {}
                        this.itemObjCopy = {}
                        this.planConfigurationDtlListCopy = this.planConfigurationDtlListCopy.reduce((item, next)=>{
                            if(!this.itemObjCopy[next.yearBudgetDtlId]) {
                                item.push(next)
                                this.itemObjCopy[next.yearBudgetDtlId] = true
                            }
                            return item
                        }, [])
                        this.planConfigurationDtlList = this.planConfigurationDtlList.reduce((item, next)=>{
                            if(next.changeType == -1) {
                                item.push(next)
                            }else{
                                if(!this.itemObj[next.yearBudgetDtlId]) {
                                    item.push(next)
                                    this.itemObj[next.yearBudgetDtlId] = true
                                }
                            }
                            return item
                        }, [])
                    })
                }
            })
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.buyPlanDtlId) {
                this.currentRow.changeType = 2
            }
            this.onAmount(row)
        },
        //如果是-1就隐藏
        tableRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //计算金额 = 数量*单价
        onAmount  (row) {
            row.amount = count.onPlanBuyAmount(row.quantity, row.price)
            this.onUpCollect()
        },
        //费用合计（元） = 明细获取金额向上汇总
        onUpCollect () {
            this.formData.planBuy.purchaseCost = null
            this.formData.planBuy.purchaseCost = count.onPlanBuyUpCollect(this.planConfigurationDtlList)
            this.onScSumCost ()
        },
        //费用合计（本位币）= 费用合计*本位币汇率
        onScSumCost () {
            this.formData.planBuy.baseCurBudgetAmount = new Number(+this.formData.planBuy.purchaseCost * +this.formData.planBuy.baseCurRate).toFixed(2)
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //单个删除计划明细
        handleDelete (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    let length = this.errorMsg.length
                    if(row.buyPlanDtlId) {
                        this.$set(this.planConfigurationDtlList[$index], 'changeType', -1)
                        this.planConfigurationDtlListCopy.splice($index, 1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                    }else{
                        this.planConfigurationDtlList.splice($index, 1)
                        this.planConfigurationDtlListCopy.splice($index, 1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                    }
                }
            )
        },
        //点击删除弹窗
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }

        },
        //批量删除计划明细
        delete () {
            let length = this.errorMsg.length
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item=>{
                    if(item.buyPlanDtlId) {
                        this.$set(item, 'changeType', -1)
                        for(let i = this.planConfigurationDtlListCopy.length; i > 0; i--) {
                            if(this.planConfigurationDtlListCopy[i - 1] === item) {
                                this.planConfigurationDtlListCopy.splice(i - 1, 1)
                            }
                        }
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                        this.$refs.planTable.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.planConfigurationDtlList.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.planConfigurationDtlList[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlList.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                                if(this.planConfigurationDtlListCopy[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlListCopy.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.planTable.clearSelection()
                    }
                })
            }
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.planConfigurationDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.specificationModel === null || item.specificationModel === '') {
                            let str = `请填写第 ${index + 1} 行的（规格型号）`
                            this.errorMsg.push(str)
                        }
                        if(item.quantity === null || item.quantity === '') {
                            let str = `请填写第 ${index + 1} 行的（数量）`
                            this.errorMsg.push(str)
                        }
                        if(+item.quantity == 0) {
                            let str = `请填写第 ${index + 1} 行的（数量必须大于0）`
                            this.errorMsg.push(str)
                        }
                        if(item.price === null || item.price === '') {
                            let str = `请填写第 ${index + 1} 行的（单价（元））`
                            this.errorMsg.push(str)
                        }
                        if(+item.price == 0) {
                            let str = `请填写第 ${index + 1} 行的（单价（元）必须大于0）`
                            this.errorMsg.push(str)
                        }
                        if(item.predictTime === '' || item.predictTime == null) {
                            let str = `请选择第 ${index + 1} 行的（预计进场时间）`
                            this.errorMsg.push(str)
                        }
                    }
                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }

            })

        },
        /*
            变更历史
        */
        //获取计划明细表格的选择项
        changeHistoryTableSelect (selection) {
            this.changeHistorySelect = selection
        },
        handleDeleteHistory (row) {
            let billids = [row.billId]
            if(row.state !== 0) {
                this.clientPop(
                    'info',
                    '只要草稿状态才可以删除！',
                )
                this.$refs.changeHistorySelect.clearSelection()
            }else{
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    ()=>{
                        request.purchasePlanDelete(billids).then(()=>{
                            this.init()
                            this.clientPop('suc', '删除成功')
                            this.$refs.changeHistorySelect.clearSelection()
                        })
                    })
            }

        },
        //删除草稿状态的变更历史
        handleChangeHistory () {
            const length = this.changeHistorySelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.changeHistorySelect.forEach(item=>{
                    if(item.state !== 0) {
                        this.clientPop(
                            'info',
                            '只有草稿状态才可以删除！',
                        )
                        this.$refs.changeHistorySelect.clearSelection()
                    }else{
                        this.clientPop(
                            'info',
                            this.moreDeleteErr(length),
                            this.deleteChangeHistory
                        )
                    }
                })
            }
        },
        //批量或单独删除变更历史
        deleteChangeHistory () {
            let billids = []
            this.changeHistorySelect.forEach(item=>{
                if(item.state === 0) {
                    billids.push(item.billId)
                    request.purchasePlanDelete(billids).then(()=>{
                        this.init()
                        this.clientPop('suc', '删除成功')
                        this.$refs.changeHistorySelect.clearSelection()
                    })
                }
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/housePurchasePlanList')
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.updatePurchasePlanBaseInfo(this.formData).then(()=>{
                    this.verifyTable().then(()=>{
                        request.updatePurchasePlanInfo(this.planConfigurationDtlList).then(()=>{
                            resolve()
                        }).catch(err=>{
                            this.setError('changeDetail')
                            this.scorllError()
                            reject(err)
                        })
                    }).catch(err=>{
                        this.setError('changeDetail')
                        this.scorllError()
                        reject(err)
                    })
                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //更新计划明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    request.updatePurchasePlanInfo(this.planConfigurationDtlList).then(()=>{
                        resolve()
                    }).catch(err=>{
                        this.setError('changeDetail')
                        this.scorllError()
                        reject(err)
                    })
                }).catch(err=>{
                    this.setError('changeDetail')
                    this.scorllError()
                    reject(err)
                })
            })

        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            if(this.planConfigurationDtlListCopy.length === 0) {
                let str = '计划明细不能空！'
                this.errorMsg.push(str)
                this.setError('changeDetail')
                this.scorllError()
                return
            }
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            submitCommit(this, requestFn, 0)
        },
        //删除单据
        deleteBills () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    let billids = [this.billid]
                    request.purchasePlanDelete(billids).then(()=>{
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                })
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 0)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}
.e-table {
    background: #fff;
}
</style>
